package www.way2inbox.comm;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpConnection;
import org.apache.http.HttpConnectionMetrics;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;


import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.webkit.CookieManager;

import www.way2inbox.common.PrintMsg;
import www.way2inbox.common.Urls;


public class SimpleHttpClient {
	
	/** The time it takes for our client to timeout */
    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

    /** Single instance of our HttpClient */
    private static HttpClient mHttpClient;
    
    

    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with connection parameters set
     */
    private static HttpClient getHttpClient() {
    	//System.out.println("In http class :");
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        //System.out.println("returning mhttpclient");
        return mHttpClient;
    }


    public static String executeHttpPost(String url, JSONObject obj) throws Exception {
    	String response_str = null;
//    	System.out.println("In simple http class >>>>>>>>>>>> "+obj.toString());
//    	com.google.analytics.tracking.android.Log.w("In simple http class >>>>>>>>>>>> "+obj.toString());
        BufferedReader in = null;
        String St="";
        String mSes="";
        try {
        	HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(url);
            //System.out.println("for HttpPost in SimpleHttpClient and executeHttpPost method");
         //   request.setHeader("Accept","application/xml");
            request.setHeader("User-Agent","Android-AEApp,ID=2435743");
           // cookies = request.getCookieStore().getCookies();
            request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();

            Log.e("Sending Data :","--"+url+"--"+obj.toString());
            
            EncryptDecrypt desEncrypter = new EncryptDecrypt("DES", "112325178291091200120358112325178291091200120");
//            
            String enc = desEncrypter.encrypt(obj.toString());
            
            String encrypteddata =  enc;
            
//            System.out.println("Encrypted json object is .............. : "+encrypteddata);
            
            postParameters.add(new BasicNameValuePair("json",encrypteddata));
            
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);

            request.setEntity(formEntity);
            Urls urls=new Urls();
            
            System.out.println("URL _--------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+url.toString()+"json="+encrypteddata);
//            if(!url.equals(urls.Loginurl) && !url.equals(urls.MobileVerification) && !url.equals(urls.SendSMS)){
            request.setHeader("Host",url.substring(7,url.indexOf(".com")+4));
//            }
//            else{
//            	request.setHeader("Host",urls.LocalIP);
//            }
              // connection.setRequestProperty("Keep-Alive", "115");
            Log.e("URLS  : ", url);
	        request.setHeader("Connection", "keep-alive");

//	        if(!url.equals(urls.Loginurl) && !url.equals(urls.MobileVerification)  && !url.equals(urls.SendSMS)){
	        request.setHeader("Referer", url.substring(7,url.indexOf(".com")+4));
//	        }
//            else{
//            	request.setHeader("Referer",urls.LocalIP);
//            }
	        //System.out.println("Going to check the if condition for Cookie");
	        if(obj.has("Cookie")){
	        	request.setHeader("Cookie",obj.get("Cookie").toString());
	        	//System.out.println("Going to print the cookie : "+obj.get("Cookie").toString());
	        }
	        //System.out.println("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww");
	          
            HttpResponse response = client.execute(request);
            
           
            HttpEntity responseEntity = response.getEntity();
            
            response_str =EntityUtils.toString(responseEntity, HTTP.UTF_8);
//          System.out.println("jjjjjjjjjjjjjjjjj             >>>>>>>>>>>>"+response_str);
          Log.e("Response : ", response_str);
           
            return response_str;
        }catch(Exception ex){
        	ex.printStackTrace();
//        	JSONObject jsvn = null;
//        	jsvn.put("CODE", 0020);
//        	jsvn.put("MESSAGE", "Please checkout the network connection");
//        	response_str = jsvn.toString();
//        	return response_str;
        	return "error";
        	//return ex.getMessage().toString();
        }
        finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpGet(String url) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        }
        finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
	

}
